﻿using CalligraphyEditor.CalligraphyData;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace CalligraphyEditor.ViewModel
{
    public class VMRubbings
    {
        private CollectionViewSource _cvs;

        public CollectionViewSource Cvs
        {
            get { return _cvs; }
        }

        private ObservableCollection<T_Rubbing> _ocl;

        private T_StelePaper _sp;

        public VMRubbings(T_StelePaper sp)
        {
            _sp = sp;
            var q = from r in CalligraphyEditor.App.Entities.T_Rubbing.Expand("T_Photo").Expand("T_StelePaper").Expand("T_Dynast") where (r.IsDeleted == null || r.IsDeleted == false) && r.StelePaperID == sp.ID select r;
            _ocl = new ObservableCollection<T_Rubbing>(q);
            _cvs = new CollectionViewSource();
            _cvs.Source = _ocl;
        }

        public void Add()
        {
            T_Rubbing r = new T_Rubbing();
            r.StelePaperID = _sp.ID;
            r.T_StelePaper = _sp;
            r.Name = "拓本";
            CalligraphyEditor.App.Entities.AddToT_Rubbing(r);
            CalligraphyEditor.App.Entities.SaveChanges();
            _ocl.Add(r);
        }

        public void Save()
        {
            CalligraphyEditor.App.Entities.UpdateObject(_cvs.View.CurrentItem);
            CalligraphyEditor.App.Entities.SaveChanges();
        }

        public void Delete()
        {
            T_Rubbing r = _cvs.View.CurrentItem as T_Rubbing;
            r.IsDeleted = true;
            CalligraphyEditor.App.Entities.UpdateObject(r);
            CalligraphyEditor.App.Entities.SaveChanges();
            _ocl.Remove(r);
        }

        public bool UploadPhoto()
        {
            var photo = PhotoHelper.BrowserAndUploadPhoto();
            if (photo != null)
            {
                T_Rubbing r = _cvs.View.CurrentItem as T_Rubbing;
                r.PhotoID = photo.ID;
                r.T_Photo = photo;
                photo.T_Rubbing.Add(r);
                CalligraphyEditor.App.Entities.UpdateObject(r);
                CalligraphyEditor.App.Entities.SaveChanges();
                return true;
            }
            return false;
        }
    }
}
